import { sqliteTable, index, text, integer } from 'drizzle-orm/sqlite-core';
import { relations } from 'drizzle-orm';
import { auditSchema } from './audit';
import * as feeds from './feeds';
import * as users from './users';

export const tableName = 'links';

export const route = 'links';

export const definition = {
  id: text('id').primaryKey(),
  url: text('url'),
  title: text('title'),
  user_id: text('user_id')
    .notNull()
    .references(() => users.table.id),
  feed_id: text('feed_id')
    .notNull()
    .references(() => feeds.table.id),
  driver: text('driver'),
  folderId: text('folderId'),
  checked: integer('checked').default(1), // 0 或 1
  saved: integer('saved').default(0), // 0 或 1
};

export const table = sqliteTable(
  tableName,
  {
    ...definition,
    ...auditSchema,
  },
  (table) => {
    return {
      linkUserIdIndex: index('linkUserIdIndex').on(table.user_id),
      linkFeedIdIndex: index('linkFeedIdIndex').on(table.feed_id),
    };
  }
);

export const relation = relations(table, ({ one }) => ({
  feed: one(feeds.table, {
    fields: [table.feed_id],
    references: [feeds.table.id],
  }),
  user: one(users.table, {
    fields: [table.user_id],
    references: [users.table.id],
  }),
}));
